import * as api from "@/api";

export default {
  namespaced: true,

  state: {
    lists: [],
  },

  getters: {
    //  全部列表
    getterLists: ({ lists }) => (boardId) =>
      lists.filter((list) => list.boardId === parseInt(boardId)),

    //  单个列表
    getterList: ({ lists }) => (listId) =>
      lists.find((list) => list.id == listId),
  },

  mutations: {
    //  在不刷新页面的情况下，多次进入不同的面板都会缓存下来
    //  不用每次进入不同的面板就去拉取数据
    updateLists: (state, data) => {
      state.lists = data;
    },

    editList: (state, data) => {
      state.lists = state.lists.map((list) => {
        if (list.id === data.id) {
          return data;
        }

        return list;
      });
    },
  },

  actions: {
    getLists: async ({ commit }, boardId) => {
      let { data } = await api.getLists(boardId);

      commit("updateLists", data);
    },

    postList: async ({ commit }, body) => {
      await api.postList(body);

      let { data } = await api.getLists(body.boardId);

      commit("updateLists", data);
    },

    editList: async ({ commit }, body) => {
      let { data } = await api.putList(body);

      commit("editList", data);
    },
  },
};
